package link.cocoon.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import link.cocoon.common.base.BaseController;
import link.cocoon.blog.entity.Category;
import link.cocoon.blog.service.ArticleService;
import link.cocoon.blog.service.CategoryService;
import link.cocoon.common.resp.RespData;
import link.cocoon.common.entity.TreeNode;
import link.cocoon.common.util.TreeUtil;
import link.cocoon.common.exception.RelationCheckException;
import link.cocoon.system.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Cocoon
 * @since 2020-03-31
 */
@RestController
@RequestMapping( "/blog/category" )
public class CategoryController extends BaseController<Category, CategoryService> {

  @Resource
  private ArticleService articleService;

  @Override
  public RespData<Integer> create(@RequestBody Category model) {
    User user = getCurrentUser();
    if (user == null) {
      return RespData.error("请重新登陆后尝试");
    }
    model.setCreateBy(user.getId());
    return super.create(model);
  }

  @Override
  public RespData<String> delete(@PathVariable Long id) {
    Category category = getService().getById(id);
    long count = articleService.countByCategoryId(category.getId());
    if (count > 0) {
      throw new RelationCheckException(this.getClass(), "分类下有" + count + "个文章，无法删除");
    }

    return super.delete(id);
  }

  @Override
  protected LambdaQueryWrapper<Category> getWrapper(Map<String, String> params) {
    LambdaQueryWrapper<Category> wrapper = super.getWrapper(params);
    if (params.get("parentId") != null) {
      Long categoryId = Long.valueOf(params.get("parentId"));
      List<Long> categoryIdList = getService().findAllChildrenIdById(categoryId);
      wrapper.in(Category::getParentId, categoryIdList);
    }
    return wrapper;
  }

  @GetMapping( "/tree" )
  public RespData<TreeNode> getTree() {
    List<Category> categoryList = getService().list();
    TreeNode treeNode = TreeUtil.getInitTree(categoryList);
    return RespData.success(treeNode);
  }

}

